/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session.manager;

import com.sun.org.apache.xml.internal.security.utils.Base64;
import entity.User;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import util.Digest;

/**
 *
 * @author antonio
 */
@Stateless
public class UserManagerBean implements UserManagerBeanLocal {
    
    @PersistenceContext(unitName = "BrowserGame-ejbPU")
    private EntityManager entityManager;
    
    @Resource (name = "messageDigestAlgorithm")
    private String messageDigestAlgorithm;
    
    @Override
    public User find(String username) {
        return this.entityManager.find(User.class, username);
    }
    
    @Override
    public void changePassword(String username, String password) {
        User user = this.entityManager.find(User.class, username);
        String hashPsw = null;
        try {
            hashPsw = Digest.digest(password, messageDigestAlgorithm);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(UserManagerBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(UserManagerBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        user.setPassword(hashPsw);
    }

    @Override
    public void changeEmail(String username, String email) {
        User user = this.entityManager.find(User.class, username);
        user.setEmail(email);
    }
    
    @Override
    public void deleteUser(String username) {
        User user = this.entityManager.find(User.class, username);
        this.entityManager.remove(user);
    }
    
}
